package com.bsj.pay.controller.admin;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.mysql.cj.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.bsj.pay.common.Result;
import com.bsj.pay.model.UserBean;
import com.bsj.pay.service.LogService;
import com.bsj.pay.service.UserService;
import com.bsj.pay.util.GoogleCode;
import com.bsj.pay.util.security.MD5;
import com.bsj.pay.util.security.PassWrodsCreater;
import com.github.pagehelper.PageInfo;

@Controller("adminUserController")
@RequestMapping("/admin/user")
public class UserController {
	@Autowired
	private UserService userService;
	
	@Autowired
	private LogService logService;
	
	public static String key="";
	
	@ResponseBody
	@RequestMapping("/login.html")
    public Result login(HttpSession session,HttpServletRequest request,HttpServletResponse response,ModelAndView mav,UserBean user) {
		Result result=new Result();
		if(user==null)
		{
			result.setCode(101);
			result.setMsg("参数错误");
			return result;
		}
		if(StringUtils.isNullOrEmpty(user.getAccount()))
		{
			result.setCode(102);
			result.setMsg("请输入账号");
			return result;
		}
		if(StringUtils.isNullOrEmpty(user.getPassword()))
		{
			result.setCode(103);
			result.setMsg("请输入密码");
			return result;
		}
		logService.addLog(request, "用户登录:"+user.getAccount());
		user.setPassword(MD5.getMD5(user.getPassword()));
		List<UserBean> users=userService.queryList(user);
		if(users==null||users.size()==0)
		{
			result.setCode(104);
			result.setMsg("用户名或密码错误");
			return result;
		}
		UserBean loginUser=users.get(0);
		if (!StringUtils.isNullOrEmpty(loginUser.getVcode()))
	    {
	      if (StringUtils.isNullOrEmpty(user.getVcode()))
	      {
	        result.setCode(108);
	        result.setMsg("请输谷歌验证码");
	        return result;
	      }
	      if (!GoogleCode.authcode(user.getVcode(), loginUser.getVcode()).booleanValue())
	      {
	        result.setCode(305);
	        result.setMsg("谷歌验证码错误");
	        return result;
	      }
	    }
		if(loginUser.getStatus()==0)
		{
			result.setCode(105);
			result.setMsg("账号被禁用");
			return result;
		}
		result.setCode(0);
		result.setMsg("登录成功");
		request.getSession().setAttribute("auser", loginUser);
		request.getSession().setMaxInactiveInterval(60*60);
		this.key=request.getRequestedSessionId();
		logService.addLog(request, "管理员登录成功:"+user.getAccount());
		return result;
    }
	
	
	@ResponseBody
	@RequestMapping(value = "/list.html")
	public Map list(HttpServletRequest req, HttpServletResponse res,int page,int limit,UserBean user) 
	{
		logService.addLog(req, "查看管理员列表,第"+page+"页");
		UserBean queryModel=new UserBean();
		if(!StringUtils.isNullOrEmpty(user.getName()))queryModel.setName(user.getName());
		if(!StringUtils.isNullOrEmpty(user.getAccount()))queryModel.setAccount(user.getAccount());
		if(user.getStatus()!=null)queryModel.setStatus(user.getStatus());
		PageInfo<UserBean> pageInfo=userService.pageList(queryModel, page, limit);
		List<UserBean> list=pageInfo.getList();
		Map map =new HashMap();
		map.put("code", 0);
		map.put("msg", "查询成功");
		map.put("count", pageInfo.getTotal());
		map.put("data", list);
		return map; 
	}
	
	@ResponseBody
	@RequestMapping("/updatePassword.html")
	public Result updatePassword(HttpServletRequest request,HttpServletResponse response,String password,String password1){
		Result result=new Result();
		if(StringUtils.isNullOrEmpty(password))
		{
			result.setCode(1);
			result.setMsg("请输入原始密码");
			return result;
		}
		if(StringUtils.isNullOrEmpty(password1))
		{
			result.setCode(1);
			result.setMsg("请输入新密码");
			return result;
		}
		if(!password1.equals(password))
		{
			result.setCode(1);
			result.setMsg("两次输入密码不一致");
			return result;
		}
		UserBean auser=(UserBean) request.getSession().getAttribute("auser");
		UserBean adminUser=new UserBean();
		adminUser.setId(auser.getId());
		adminUser.setPassword(MD5.getMD5(password));
		userService.update(adminUser);
		logService.addLog(request, "管理员修改密码");
		result.setCode(0);
		result.setMsg("修改成功");
		return result;
	}
	
	@RequestMapping("/listPage.html")
	public ModelAndView usersListPage(HttpServletRequest request,HttpServletResponse response,ModelAndView mav)
	{
		mav.setViewName("admin/user/list");
		return mav;
	}
	
	@RequestMapping("/addPage.html")
	public ModelAndView addPage(HttpServletRequest request, HttpServletResponse response, HttpSession session,ModelAndView mav) {
		mav.setViewName("admin/user/add");
		return mav;
	}
	
	
	@ResponseBody
	@RequestMapping("/add.html")
	public Result add(HttpServletRequest request,HttpServletResponse response,ModelAndView mav,UserBean user)
	{
		Result result=new Result();
		if(user==null)
		{
			result.setCode(1);
			result.setMsg("参数错误");
			return result;
		}
		try {
			UserBean queryModel=new UserBean();
			queryModel.setAccount(user.getAccount());
			if(userService.count(queryModel)>0)
			{
				result.setCode(1);
				result.setMsg("账号已存在");
				return result;
			}
			user.setCreate_time(System.currentTimeMillis()/1000);
			user.setUpdate_time(System.currentTimeMillis()/1000);
			String password=PassWrodsCreater.generatePassword(6);
			user.setPassword(MD5.getMD5(password));
			userService.insert(user);
			logService.addLog(request, "新增管理员:"+user.getAccount());
			result.setCode(0);
			result.setMsg("添加成功,密位为"+password);
			return result;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			result.setCode(500);
			result.setMsg(e.getMessage());
			return result;
		}
		
	}
	
	@ResponseBody
	@RequestMapping(value = "/updateStatus.html")
	public Result updateStatus(HttpServletRequest req, HttpServletResponse res,Long id,Integer status) {
		Result result=new Result();
		try {
			UserBean user=new UserBean();
			user.setId(id);
			user.setStatus(status==0?1:0);
			if(userService.update(user)>0)
			{
				result.setCode(0);
				result.setMsg("修改成功");
			}
			else
			{
				result.setCode(1);
				result.setMsg("修改失败");
			}
			
			return result;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			result.setCode(500);
			result.setMsg(e.getMessage());
			return result;
		}

	}
	
	@ResponseBody
	@RequestMapping("/resetPassword.html")
	public Result resetPassword(HttpServletRequest request,HttpServletResponse response,Long id){
		Result result=new Result();
		UserBean adminUser = new UserBean();
		adminUser.setId(id);
		String password=PassWrodsCreater.generatePassword(6);
		adminUser.setPassword(MD5.getMD5(password));
		userService.update(adminUser);
		logService.addLog(request, "重置管理员密码,ID:"+id);
		result.setCode(0);
		result.setMsg("重置成功,新密码为"+password);
		return result;
	}
	
	/**
	 * 修改用户信息
	 * @param request
	 * @param response
	 * @param session
	 * @param mav
	 * @param userId
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/update.html")
	public Map<String,Object> updatePage(HttpServletRequest request, HttpServletResponse response, HttpSession session,ModelAndView mav,UserBean user) {
		Map<String,Object> map = new HashMap<String,Object>();
		UserBean updateUser = new UserBean();
		updateUser.setId(user.getId());
		updateUser.setRemarks(user.getRemarks());
		updateUser.setName(user.getName());
		updateUser.setVcode(user.getVcode());
		userService.update(updateUser);
		logService.addLog(request, "修改管理员:"+user.getAccount());
		map.put("code", 0);
		map.put("msg", "修改成功");
		return map;
		
	}
	
	@ResponseBody
	@RequestMapping(path={"/code.html"})
	public Result code(HttpServletRequest req, HttpServletResponse res)
	{
	    Result result = new Result();
	    result.setCode(1);
	    result.setMsg(GoogleCode.generateSecretKey());
	    return result;
	}
	
	@RequestMapping("/updatePage.html")
	public ModelAndView updatePage(HttpServletRequest request,HttpServletResponse response,ModelAndView mav,Long uid)
	{	
		UserBean user=userService.getById(uid);
		mav.addObject("user", user);
		mav.setViewName("admin/user/update");
		return mav;
	}

	@ResponseBody
	@RequestMapping(value = "/remove.html")
	public Result remove(HttpServletRequest req, HttpServletResponse res,Long id) {
		Result result=new Result();
		try {
			if(userService.removeById(id)>0)
			{
				result.setCode(0);
				result.setMsg("删除成功");
				logService.addLog(req, "删除账号,ID:"+id);
			}
			else
			{
				result.setCode(1);
				result.setMsg("删除失败");
			}
			
			return result;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			result.setCode(500);
			result.setMsg(e.getMessage());
			return result;
		}

	}
}
